// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import VueRouter from 'vue-router'
import Vuex from 'vuex'

import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'

import App from './App'
import routers from './router'
import stores from './store'
import serviceApi from './api/service.js'

Vue.use(VueRouter)
Vue.use(Vuex)
Vue.use(ElementUI)

const router = new VueRouter(routers)
const store = new Vuex.Store(stores)
Vue.config.productionTip = false
Vue.prototype.$axios = serviceApi

// 路由导航
// 去的路径不包含在路由表中则返回登录页
// 去的路径不包括登陆凭证accessToken，则返回登陆页('/'和'/Login'不验证)

router.beforeEach((to, from, next) => {
  // 所有路由
  let allRouters = []
  routers.routes.forEach(route => {
    if (route.children) {
      route.children.forEach(childRoute => {
        allRouters.push(`${route.path}/${childRoute.path}`)
      })
    } else {
      allRouters.push(route.path)
    }
  })
  // 登录凭证 accessToken
  const accessToken = sessionStorage.getItem('accessToken')
  let isToRouteExist = allRouters.some(toVal => {
    if (toVal !== '/' && toVal !== '/Login') {
      return toVal === to.path && Boolean(accessToken)
    } else {
      return toVal === to.path
    }
  })
  if (!isToRouteExist) {
    next({
      path: '/'
    })
  } else {
    next()
  }
})

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  components: {
    App
  },
  template: '<App/>'
})
